#!/bin/bash
# 创建集群
{% if "hostvars[ansible_default_ipv4.address].redis_password is not defined" %}
    echo "yes"|redis-cli --cluster create {% for master_host in groups['cluster_master'] %} {{ master_host }}:{{ hostvars[ansible_default_ipv4.address].redis_port }}  {% endfor %} --cluster-replicas 0
{% else %}
    echo "yes"|redis-cli -a {{ hostvars[ansible_default_ipv4.address].redis_password }}  --no-auth-warning --cluster create {% for master_host in groups['cluster_master'] %} {{ master_host }}:{{ hostvars[ansible_default_ipv4.address].redis_port }}  {% endfor %} --cluster-replicas 0
{% endif %}
sleep 3
# 添加从节点
#redis-cli --cluster add-node 10.0.0.101:6391 10.0.0.101:6380 --cluster-slave --cluster-master-id $(redis-cli -c -h 127.0.0.1 -p 6380 cluster nodes|awk '/101:6390/{print $1}')
{% if "hostvars[ansible_default_ipv4.address].redis_password is not defined" %}
    {% set sorted_groups = groups['cluster_master']|sort %}  
    {% for slave_host in groups['cluster_slave']|sort %}
        redis-cli --cluster add-node {{ slave_host }}:{{ hostvars[ansible_default_ipv4.address].redis_port }} {{ sorted_groups[loop.index0] }}:{{ hostvars[ansible_default_ipv4.address].redis_port }} --cluster-slave --cluster-master-id $(redis-cli  -c -h 127.0.0.1 -p {{ hostvars[ansible_default_ipv4.address].redis_port }} cluster nodes|awk '/{{ sorted_groups[loop.index0] }}:{{ hostvars[ansible_default_ipv4.address].redis_port }}/{print $1}')
    {% endfor %}
{% else %}
    {% set sorted_groups = groups['cluster_master']|sort %}  
    {% for slave_host in groups['cluster_slave']|sort %}
        redis-cli  -a {{ hostvars[ansible_default_ipv4.address].redis_password }} --no-auth-warning --cluster add-node {{ slave_host }}:{{ hostvars[ansible_default_ipv4.address].redis_port }} {{ sorted_groups[loop.index0] }}:{{ hostvars[ansible_default_ipv4.address].redis_port }} --cluster-slave --cluster-master-id $(redis-cli -a {{ hostvars[ansible_default_ipv4.address].redis_password }} --no-auth-warning -c -h 127.0.0.1 -p {{ hostvars[ansible_default_ipv4.address].redis_port }} cluster nodes|awk '/{{ sorted_groups[loop.index0] }}:{{ hostvars[ansible_default_ipv4.address].redis_port }}/{print $1}')
    {% endfor %}
{% endif %}